import axios from 'axios';
import hCore from "hui-core";
import { hMessage } from "h_ui"

// 抛出 http 异常
const HttpError = (message, code) => {
  const error = new Error(message);
  error.name = 'HttpError';
  if (code != null) {
    error.code = code;
  }

  return Promise.reject(error);
};

// 创建axios实例
const service = axios.create({
  baseURL: '/',
  timeout: 5 * 60 * 1000, // 请求超时时间
});

// request拦截器
service.interceptors.request.use(
  (config) => {
    // document.cookie = 'token=1311224e-0ece-4903-ae6a-72038c0f3c504';
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // 如果请求的返回类型是流，则直接返回 data
    if (response.config.responseType === 'blob') {
      return response;
    }
    let { return_code, result, error_code, error_message } = res;

    if(!return_code){
      return res; 
    }
		if (error_code === '401') {
			hCore.navigate('/login');
			return;
		}

    if(!!error_code || (return_code!==200 && return_code!=0)){
			hMessage.error({
				content: error_message,
				duration: 3,
			})
      return HttpError(error_message || '请求异常', error_code);
    }

    return result;
  },
  (error) => {
    if (error.response) {
      const { status } = error.response;
      // 目前后端返回会出现有 code 无 msg
      if (status === 401) {
        hCore.navigate('/login');
        return;
      } 
				
			hMessage.error({
				content: error?.response?.data?.error_info || error.response.statusText,
				duration: 3,
			})

      return HttpError(`请求异常：${error.response.statusText}`);
    }

    if (error.request) {
      return HttpError('请求异常：无返回结果');
    }

    return HttpError(error.message);
  }
);

const useGet = (url, params = {}) => {
  return service.get(url, { params });
};

const usePost = (url, jsonData) => {
  return service.post(url, jsonData);
};

export { useGet, usePost, service };
